package com.jerry.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jerry.waimai.common.R;
import com.jerry.waimai.entity.User;
import com.jerry.waimai.service.UserService;
import com.jerry.waimai.utils.SMSUtils;
import com.jerry.waimai.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code = {}", code);
            //调用阿里云提供的短信服务API完成发送短信
            SMSUtils.sendMessage("waimai","SMS_296850027", phone, code);
            //需要将生成的验证码保存到Session
            session.setAttribute(phone, code);

            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 移动端用户登录
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session){
        //获取手机号
        String phone = user.get("phone").toString();
        //获取验证码
        String code = user.get("code").toString();
        //从Session中获取保存的验证码
        Object attribute = session.getAttribute(phone);

        //进行验证码比对（页面提交的验证码和session中保存的验证码比对）
        if(attribute != null && attribute.equals(code)){
            //如果能够比对成功，说明登录成功
            //判断当前手机号对应的用户是否为新用户，如果是新用户自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);

            User one = userService.getOne(queryWrapper);
            if(one == null){
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user", one.getId());
            return R.success(one);
        }

        return R.error("登陆失败");
    }

    /**
     * 移动端用户退出
     * @return
     */
    @PostMapping("loginout")
    public R<String> loginOut(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("用户注销成功");
    }
}
